import { useEffect, useState, useRef, useMemo } from 'react';
import axios from '../../api/index';
import './index.scss'
import { Tabs } from 'antd-mobile';
import SimplePurchaseModal from '../../component/type';

// 定义类型
interface VideoCategory {
  id: number;
  name: string;
}

interface VideoItem {
  id: number;
  title: string;
  shearUrl?: string;
  originalUrl?: string;
  abstracts?: string;
  whetherBuy?: number;
  buyNum?: number;
  price?: number;
  duration?: number;
  whetherCollection?: number;
}

interface DanmakuItem {
  id: number;
  content: string;
  color: string;
  top: number;
  speed: number;
  delay: number;
}


function Sp() {
  const [list, setList] = useState<VideoCategory[]>([]);
  const [dataList, setDataList] = useState<VideoItem[]>([]);
  const [categoryId, setCategoryId] = useState<number>(1);
  const [page] = useState<number>(1);
  const [count] = useState<number>(5);
  const [favorites, setFavorites] = useState<Set<number>>(new Set());
  const [danmakuList, setDanmakuList] = useState<DanmakuItem[]>([]);
  const [currentVideoId, setCurrentVideoId] = useState<number | null>(null);
  const [danmakuEnabled, setDanmakuEnabled] = useState<boolean>(true);
  
  // 购买弹窗相关状态
  const [showPurchaseModal, setShowPurchaseModal] = useState(false);
  const [selectedVideo, setSelectedVideo] = useState<VideoItem | null>(null);
  const [userCoins, setUserCoins] = useState(175); // 用户金币余额
  
  // 存储视频元素的ref
  const videoRefs = useRef<(HTMLVideoElement | null)[]>([]);
  // 存储内容容器的ref
  const contentRef = useRef<HTMLDivElement>(null);
  // 存储弹幕容器的ref
  const danmakuRef = useRef<HTMLDivElement>(null);

  // 切换弹幕开关
  const toggleDanmaku = () => {
    setDanmakuEnabled(!danmakuEnabled);
    if (!danmakuEnabled) {
      // 如果开启弹幕，清空现有弹幕重新开始
      setDanmakuList([]);
    }
  };

  // 模拟弹幕数据
  const mockDanmakuData = useMemo(() => [
    "视频真实", "哇哇", "厉害", "社会", "可口",
    "这小身板不容小觑", "哥们好帅", "牛牛",
    "个可以有", "这个视频这个价可以值得拥有!",
    "很专业", "学到了", "太棒了", "666",
    "收藏了", "转发", "赞一个", "支持"
  ], []);


  // 持续生成新弹幕
  useEffect(() => {
    if (!currentVideoId || !danmakuEnabled) return;
    
    const interval = setInterval(() => {
      const content = mockDanmakuData[Math.floor(Math.random() * mockDanmakuData.length)];
      const color = '#ffffff'; // 全部白色
      const top = Math.random() * 20 + 10;
      const speed = Math.random() * 1.5 + 2;
      const delay = 0;
      
      const newDanmaku: DanmakuItem = {
        id: Date.now(),
        content,
        color,
        top,
        speed,
        delay
      };
      
      setDanmakuList(prev => [...prev, newDanmaku]);
    }, 2000); // 每2秒生成一条新弹幕
    
    return () => clearInterval(interval);
  }, [currentVideoId, mockDanmakuData, danmakuEnabled]);

  // 获取视频分类列表
  useEffect(() => {
    axios.get('/user/video/v1/findVideoCategoryList').then((res) => {
      setList(res.data.result);
      // 如果有分类数据，默认选中第一个
      if (res.data.result.length > 0) {
        setCategoryId(res.data.result[0].id);
      }
    });
  }, []);

  // 获取视频列表数据
  useEffect(() => {
    axios.get('/user/video/v1/findVideoVoList', {
      params: { categoryId, page, count }
    }).then((res) => {
      setDataList(res.data.result);
      
      // 根据API数据初始化收藏状态
      const initialFavorites = new Set<number>();
      res.data.result.forEach((item: VideoItem) => {
        if (item.whetherCollection === 1) {
          initialFavorites.add(item.id);
        }
      });
      setFavorites(initialFavorites);
      
      // 重置滚动位置到顶部
      if (contentRef.current) {
        contentRef.current.scrollTop = 0;
      }
    });
  }, [categoryId, page, count]);

  // 自动播放第一个视频
  useEffect(() => {
    if (dataList.length > 0 && videoRefs.current[0]) {
      // 延迟一点时间确保视频元素已经渲染
      setTimeout(() => {
        const firstVideo = videoRefs.current[0];
        if (firstVideo) {
          firstVideo.play().catch((err: Error) => console.log('自动播放失败:', err));
        }
      }, 300);
    }
  }, [dataList]);

  // 监听滚动，控制视频播放状态
  useEffect(() => {
    let isScrolling = false;
    
    const handleScroll = () => {
      if (isScrolling) return;
      isScrolling = true;
      
      requestAnimationFrame(() => {
        if (!contentRef.current) {
          isScrolling = false;
          return;
        }

        // 找到当前最居中的视频
        let currentVideo: { video: HTMLVideoElement; index: number } | null = null;
        let minDistance = Infinity;

        videoRefs.current.forEach((video, index) => {
          if (!video) return;

          const rect = video.getBoundingClientRect();
          const centerY = window.innerHeight / 2;
          const videoCenterY = rect.top + rect.height / 2;
          const distance = Math.abs(videoCenterY - centerY);

          // 如果视频在可视区域内，计算距离中心的距离
          if (rect.top < centerY && rect.bottom > centerY) {
            if (distance < minDistance) {
              minDistance = distance;
              currentVideo = { video, index };
            }
          }
        });

        // 播放最居中的视频，暂停其他视频
        videoRefs.current.forEach((video, index) => {
          if (!video) return;
          
          if (currentVideo && index === currentVideo.index) {
            // 播放当前视频
            video.play().catch((err: Error) => console.log('播放失败:', err));
            // 设置当前视频ID用于弹幕生成
            if (dataList[currentVideo.index]) {
              setCurrentVideoId(dataList[currentVideo.index].id);
            }
          } else {
            // 暂停其他视频
            video.pause();
          }
        });

        isScrolling = false;
      });
    };

    const content = contentRef.current;
    if (content) {
      // 初始加载时检查一次
      setTimeout(handleScroll, 100);
      // 监听滚动事件
      content.addEventListener('scroll', handleScroll);
    }

    // 组件卸载时移除监听
    return () => {
      if (content) {
        content.removeEventListener('scroll', handleScroll);
      }
    };
  }, [dataList]); // 视频列表变化时重新监听
  // 处理购买点击
  const handlePurchase = (videoId: number) => {
    const video = dataList.find(item => item.id === videoId);
    if (video) {
      setSelectedVideo(video);
      setShowPurchaseModal(true);
    }
  };

  // 关闭弹窗
  const handleCloseModal = () => {
    setShowPurchaseModal(false);
    setSelectedVideo(null);
  };

  // 确认购买
  const handleBuy = () => {
    if (selectedVideo && userCoins >= (selectedVideo.price || 0)) {
      // 扣除金币
      setUserCoins(userCoins - (selectedVideo.price || 0));
      // 关闭弹窗
      setShowPurchaseModal(false);
      // 显示购买成功消息
      alert(`购买成功！已扣除 ${selectedVideo.price || 0} 金币`);
    }
  };

  // 充值金币
  const handleRecharge = () => {
    setUserCoins(userCoins + 100);
    alert('充值成功！获得100金币');
  };

  // 处理收藏点击
  const handleFavorite = (videoId: number) => {
    setFavorites(prev => {
      const newFavorites = new Set(prev);
      if (newFavorites.has(videoId)) {
        newFavorites.delete(videoId);
      } else {
        newFavorites.add(videoId);
      }
      return newFavorites;
    });
  };


  // 格式化购买数据
  const formatBuyNum = (buyNum?: number) => {
    if (!buyNum) return '0人';
    if (buyNum < 10000) {
      return `${buyNum}人`;
    } else {
      return `${Math.floor(buyNum / 10000)}万人`;
    }
  };

  return (
    <div className='box'>
      <Tabs 
        onChange={(key: string) => setCategoryId(Number(key))} 
        className='top'
        activeLineMode="fixed"
      >
        {list.map((item) => (
          <Tabs.Tab 
            style={{ color: 'white' }} 
            title={item.name} 
            key={item.id}
          />
        ))}
      </Tabs>
      
      <div 
        className='countent' 
        ref={contentRef}
      >
        {dataList.map((item, index) => (
          <div key={item.id} className='video-card'>
            {/* 视频容器 */}
            <div className='video-container'>
              <video
                ref={el => { videoRefs.current[index] = el; }} // 存储视频元素ref
                className='video'
                src={item.shearUrl || item.originalUrl}
                controls
                loop
                playsInline // 移动端内联播放，避免自动全屏
                preload="metadata" // 预加载元数据
              />
              
              {/* 标题覆盖层 */}
              <div className='video-title'>
                {item.title}
              </div>
              
              {/* 试看提示覆盖层 */}
              {item.whetherBuy === 2 && (
                <div className='trial-overlay'>
                  <div className='trial-text'>
                    试看<span className='highlight'>15s</span>, 购买观看完整视频
                  </div>
                </div>
              )}

              {/* 弹幕层 */}
              <div className='danmaku-container' ref={danmakuRef}>
                {danmakuEnabled && danmakuList.map((danmaku) => (
                  <div
                    key={danmaku.id}
                    className='danmaku-item'
                    style={{
                      color: danmaku.color,
                      top: `${danmaku.top}%`,
                      animationDelay: `${danmaku.delay}ms`,
                      animationDuration: `${danmaku.speed}s`
                    }}
                  >
                    {danmaku.content}
                  </div>
                ))}
              </div>

              {/* 右侧功能图标 */}
              <div className='action-icons'>
                {/* 购买图标 */}
                <div 
                  className='action-icon purchase-icon'
                  onClick={() => handlePurchase(item.id)}
                >
                  <img src="/34.png" alt="购买" className='icon-image' />
                </div>
                
                {/* 收藏图标 */}
                <div 
                  className={`action-icon favorite-icon ${favorites.has(item.id) ? 'active' : ''}`}
                  onClick={() => handleFavorite(item.id)}
                >
                  <img src="/31.png" alt="收藏" className='icon-image' />
                </div>
                
                {/* 弹幕开关图标 */}
                <div 
                  className={`action-icon danmaku-icon ${danmakuEnabled ? 'active' : ''}`}
                  onClick={toggleDanmaku}
                >
                  <img src="/35.png" alt="弹幕" className='icon-image' />
                </div>
                
                {/* 购买统计信息 */}
                <div className='purchase-stats'>
                  <div className='stats-text'>
                    <div className='stats-number'>{formatBuyNum(item.buyNum)}</div>
                    <div className='stats-label'>已购买</div>
                  </div>
                </div>
              </div>
            </div>
            
            {/* 描述文字区域 */}
            <div className='description-section'>
              <div className='description-text'>
                {item.abstracts || '健身是一种体育项目，健身可以增强力量、柔韧性，增强耐力, 提高协调, 控制身体各部分的能力, 从而使身体强健。'}
              </div>
            </div>
            
            {/* 进度条 */}
            <div className='progress-line'></div>
          </div>
        ))}
      </div>
      
      {/* 购买弹窗 */}
      <SimplePurchaseModal
        isOpen={showPurchaseModal}
        videoTitle={selectedVideo?.title || ''}
        videoPrice={selectedVideo?.price || 0}
        userCoins={userCoins}
        onClose={handleCloseModal}
        onBuy={handleBuy}
        onRecharge={handleRecharge}
      />
    </div>
  );
}

export default Sp;